const Koa = require('koa')
const Router = require('koa-router')
const cors =  require('koa2-cors')

const app = new Koa()
const router = new Router()

app.use(cors())

const views = require('koa-views')
const co = require('co')
const convert = require('koa-convert')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')
// const jwt = require('koa-jwt')
// const jsonwebtoken = require('jsonwebtoken')


const config = require('./config')
const routes = require('./routes')
const users = require('./routes/users')
const projectTwo = require('./routes/projectTwo')
const projectOne = require('./routes/proejctOne')
const projectThree = require('./routes/projectThree')
const froms = require('./routes/from')

const port = process.env.PORT || config.port


// error handler
onerror(app)

// routes
app.use(users.routes(), users.allowedMethods())
app.use(projectTwo.routes(), projectTwo.allowedMethods())
app.use(projectOne.routes(), projectOne.allowedMethods())
app.use(projectThree.routes(), projectThree.allowedMethods())

app.use(froms.routes(), froms.allowedMethods())

// middlewares
app.use(bodyparser())
  .use(json())
  .use(logger())
  .use(require('koa-static')(__dirname + '/public'))
  .use(views(path.join(__dirname, '/views'), {
    options: { settings: { views: path.join(__dirname, 'views') } },
    map: { 'njk': 'nunjucks' },
    extension: 'njk'
  }))
  .use(router.routes())
  .use(router.allowedMethods())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - $ms`)
})

router.get('/', async (ctx, next) => {
  // ctx.body = 'Hello World'
  ctx.state = {
    title: 'Koa2'
  }
  await ctx.render('index', ctx.state)
})

const { Sequelize, DataTypes } = require('sequelize')
const sequelize = new Sequelize('stage5', 'root', 'root', {
  host: 'localhost',
  dialect: 'mysql'
})

routes(router)
app.on('error', function (err, ctx) {
  console.log(err)
  logger.error('server error', err, ctx)
})

module.exports = app.listen(config.port, async () => {
  // await sequelize.sync({ force: false });
  console.log(`Listening on http://localhost:${config.port}`)
})
